<template>
  <div>
    <el-dialog :visible.sync="PurchaseDialogVisible" title="新增采购订单" width="80%" top="10vh">
      <el-form ref="form" :model="form" label-width="80px" inline>
        <el-form-item label="订单号">
          <el-input v-model="form.purchase_order_code " placeholder="请输入订单号" size="small" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="form.vendor" placeholder="请选择供应商" size="small" />
        </el-form-item>
        <el-form-item label="订单日期">
          <el-date-picker v-model="form.order_date" type="date" placeholder="选择日期" size="small" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="form.status" placeholder="请选择订单状态" size="small">
            <el-option label="已下单" value="已下单" />
            <el-option label="已发货" value="已发货" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-card class="cardTable">
        <el-table
          ref="multipleTable"
          stripe
          border
          height="65vh"
          :header-cell-style="{background:'#eef1f6',color:'#606266' }"
          :data="orderDetailData"
          :row-style="{height: '0px'}"
          :cell-style="{padding: '0px'}"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          :default-sort = "{prop: 'date', order: 'descending'}"
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            v-for="(item, index) in detailKeys"
            v-if="item.visible"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.edit" class="inputDeep">
                <el-input v-if="item.type==='string'" v-model="scope.row[item.prop]" size="small" />
                <el-select v-if="item.type==='select'" v-model="scope.row[item.prop]" size="small">
                  <el-option label="已下单" value="0" />
                  <el-option label="未发货" value="1" />
                  <el-option label="已发货" value="2" />
                  <el-option label="已完成" value="3" />
                </el-select>
              </div>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
          >
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" @click="editPurchaseOrder(scope.row)">编辑</el-button>
              <el-button type="text" icon="el-icon-delete" @click="PurchaseDialogVisible(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
    <el-row type="fixed">
      <el-col
        span="3"
      >
        <el-button type="primary" size="small" icon="el-icon-plus" @click="PurchaseDialogVisible=true">新增</el-button>
      </el-col>
      <el-col
        span="21"
      >
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="搜索">
            <el-input v-model="params.search" placeholder="Search" size="small" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-search" @click="onSearch">查询</el-button>
            <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-card class="cardTable">
      <el-table
        ref="multipleTable"
        type="index"
        stripe
        highlight-current-row
        border
        height="75vh"
        :header-cell-style="{background:'#eef1f6',color:'#606266' }"
        :data="tableData"
        :row-style="{height: '0px'}"
        :cell-style="{padding: '0px'}"
        tooltip-effect="dark"
        style="width: 100%"
        @row-dblclick="handleRowDoubleClick"
        @current-change="handleCurrentChangeRow"
      >
        :default-sort = "{prop: 'date', order: 'descending'}"
        <!--        <el-table-column-->
        <!--          type="selection"-->
        <!--          width="55"-->
        <!--        />-->
        <el-table-column
          type="index"
          width="55"
          label="序号"
        />
        <el-table-column
          v-for="(item, index) in tableKeys"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          sortable
        >
          <template slot-scope="scope">
            <div v-if="item.edit && scope.row.edit">
              <el-input v-if="item.type==='string'" v-model="scope.row[item.prop]" size="small" />
              <el-select v-if="item.type==='select'" v-model="scope.row[item.prop]" size="small">
                <el-option label="已下单" value="0" />
                <el-option label="未发货" value="1" />
                <el-option label="已发货" value="2" />
                <el-option label="已完成" value="3" />
              </el-select>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="editPurchaseOrder(scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" @click="editPurchaseOrder(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-row align="middle" type="flex" justify="center">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[14, 20, 30, 40]"
        :page-size="params.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChangePage"
      />
    </el-row>
  </div>
</template>

<script>
import {
  PurchaseDetailSearchAPI,
  PurchaseOrdersAPI, PurchaseOrderUpdateAPI
} from '@/api/purchases/purchase'
import item from '@/layout/components/Sidebar/Item.vue'

export default {
  data() {
    return {
      total: 0,
      PurchaseDialogVisible: false,
      params: {
        search: '',
        page_size: 20,
        page: 1
      },
      tableData: [],
      originTableData: [],
      orderDetailData: [],
      detailKeys: [
        { label: '采购订单', prop: 'purchase_order_code', visible: true, edit: false, type: 'string' },
        { label: '订单日期', prop: 'update_time', visible: true, edit: false, type: 'string' },
        { label: '产品名称', prop: 'product', visible: true, edit: false, type: 'string' },
        { label: '订单数量', prop: 'quantity', visible: true, edit: false, type: 'string' },
        { label: '备注', prop: 'remark', visible: true, edit: false, type: 'string' }
        // { label: '实际交货日期', prop: 'actual_delivery_date'
      ],
      tableKeys: [
        { label: '采购订单', prop: 'purchase_order_code', visible: true, edit: false, type: 'string' },
        { label: '订单日期', prop: 'order_date', visible: true, edit: false, type: 'string' },
        { label: '供应商', prop: 'vendor', visible: true, edit: false, type: 'string' },
        { label: '订单状态', prop: 'order_status', visible: true, edit: true, type: 'select' },
        { label: '订单总量', prop: 'order_total', visible: true, edit: false, type: 'string' },
        { label: '备注', prop: 'remark', visible: true, edit: true, type: 'string' }
        // { label: '要求交货日期', prop: 'requested_delivery_date', visible: true },
        // { label: '实际交货日期', prop: 'actual_delivery_date', visible: true }
      ],
      multipleSelection: [],
      formInline: {
        user: '',
        region: ''
      },
      form: {
        purchase_order_code: '',
        product: '',
        quantity: 0
      },
      dialogTableVisible: false,
      dialogFormVisible: false
    }
  },
  computed: {
    item() {
      return item
    }
  },
  async created() {
    await this.refreshPage()
  },

  methods: {
    async refreshPage(params = {}) {
      const orders = await PurchaseOrdersAPI(params)
      this.total = orders.count
      console.log(orders)
      this.tableData = orders.results.map(item => ({
        ...item,
        order_date: item.order_date.slice(0, 10),
        vendor: item.vendor.name,
        edit: false
      }))
      // this.tableData.push({ edit: true })
      this.originTableData = this.tableData.map(item => ({ ...item }))
    },
    async onSearch() {
      await this.refreshPage(this.params)
    },
    onReset() {
      this.params.search = ''
      this.refreshPage()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async editPurchaseOrder(row) {
      this.PurchaseDialogVisible = true
      console.log(row)
      const res = await PurchaseDetailSearchAPI({ search: row.purchase_order_code })
      console.log(res)
      this.orderDetailData = res.results.map(item =>
        ({
          ...item, product: this.$store.state.basic_data.products.find(item1 => item1.id === item.product).name,
          update_time: item.update_time.slice(0, 10)
        }))
      this.orderDetailData.push({ edit: true })
    },
    handleSizeChange(val) {
      this.params.page_size = val
      this.refreshPage(this.params)
      // console.log(`每页 ${val} 条`)
    },
    handleCurrentChangePage(val) {
      this.params.page = val
      this.refreshPage(this.params)
      // console.log(`当前页: ${val}`)
    },
    handleRowDoubleClick(val) {
      this.tableData.forEach(item => {
        item.edit = false
      })
      this.tableData.forEach(item => {
        if (item.purchase_order_code === val.purchase_order_code) {
          item.edit = true
        }
      })
    },
    handleCurrentChangeRow(val, oldVal) {
      this.tableData.forEach(item => {
        item.edit = false
      })
      this.tableData.forEach(item => {
        if (item.purchase_order_code === val.purchase_order_code) {
          item.edit = false
        }
      })
      if (oldVal && JSON.stringify(oldVal) !==
        JSON.stringify(this.originTableData.find(item => item.purchase_order_code === oldVal.purchase_order_code))) {
        console.log(oldVal)
        console.log(this.originTableData.find(item => item.purchase_order_code === val.purchase_order_code))
        this.savePurchaseOrder(oldVal)
      }
    },
    async savePurchaseOrder(row) {
      console.log(row)
      this.$confirm('此操作将永久修改数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await PurchaseOrderUpdateAPI(row)
        this.$message({
          type: 'success',
          message: '修改成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        })
      })
    }

    // const res = await PurchaseOrderUpdateAPI({ search: row.purchase_order_code })
    // console.log(res)
  }
}
</script>

<style lang="scss" scoped>
.table_area {
  height: 75vh;
}

.el-input {
  ::v-deep .el-input__inner {
    border: 0;
    border-radius: 0;
  }
}
</style>
